import React, { useState,useEffect, useTransition,useRef, Children  } from 'react'
import {Button, Card,Modal,Form,message,Row,Col,Input,Upload,Select, Tabs,Table,Tooltip,List } from 'antd'
import { useNavigate } from 'react-router-dom';
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { UploadOutlined,SearchOutlined  } from '@ant-design/icons';  
import {download} from '@/utils/request';
import { tslist,testlist,listSubject,listTest,addSubject,editSubject,editTest,addTest,delProject,delTest,delsubjectByTs,deltestByTs} from "@/api/modules/litermark";
import { ProFormColumnsType } from '@ant-design/pro-components'
import { listDictionary,groupList,getDictionary,delDictionary,addDictionary,updateDictionary} from "@/api/tool/dictionary";

const { TabPane } = Tabs;  
const {Option} = Select
  
const dictionary = () => {  
  const [expandedRowsTab1, setExpandedRowsTab1] = useState([]);  
  const [expandedRowsTab2, setExpandedRowsTab2] = useState([]);  
  const { t } = useTranslation()
  const [tab1Data, setTab1Data] = useState([]);  
  const [tab2Data, setTab2Data] = useState([]);  
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [isModalVisible2, setIsModalVisible2] = useState(false); 
  const [Title2, setTitle2] = useState("")  
  const [form2] = Form.useForm();  
  const [fileList, setFileList] = useState([]); 
  const [filename, setFilename] = useState(""); 
  const [isView, SetisView] = useState(false)
  const [isView2, SetisView2] = useState(false)
  const [riskdistances,setRiskdistances] = useState([]); 
  const [onReloadNum, setReloadNum] = useState(0); 
  const [onReloadNum2, setReloadNum2] = useState(0); 
  const [peoplelist,setPeople] = useState([])

  // Tab 1的列定义  
const columnsTab1 = [  
  {  
    title: t('dictionary.type'),  
    dataIndex: 'type',  
    key: 'type',  
  },  
  {  
    title: t('log.typeName'),  
    dataIndex: 'typeName',  
    key: 'typeName',  
  },  
 
]; 


  // 使用useEffect在组件挂载时获取数据  
  useEffect(() => {  
    fetchTab1Data(); 

  }, []); // 空数组意味着这个effect只在组件挂载时运行一次  

  const fetchTab1Data = async () => {  

    const { success, data} = await groupList({pageNum:1,pageSize:9999})
    if(!success) return false
    let data1 = data.rows
    for(let i=0;i<data1.length;i++){
      data1[i].key = i+1
    }
    
    setTab1Data(data1)
  };  


  const expandedColumns = [
    {  
      title: t('dictionary.nameCn'),  
      dataIndex: 'nameCn',  
      key: 'nameCn',  
      ellipsis: {
        showTitle: false,
      },
    render: (nameCn) => (
        <Tooltip placement="topLeft" title={nameCn}>
          {nameCn}
        </Tooltip>
      ),
    },  
    {  
      title: t('dictionary.nameEn'),  
      dataIndex: 'nameEn',  
      key: 'nameEn',  
      ellipsis: {
        showTitle: false,
      },
    render: (nameEn) => (
        <Tooltip placement="topLeft" title={nameEn}>
          {nameEn}
        </Tooltip>
      ),
    },    
    {  
      title: t('dictionary.oriName'),  
      dataIndex: 'oriName',  
      key: 'oriName', 
      ellipsis: {
        showTitle: false,
      },
    render: (oriName) => (
        <Tooltip placement="topLeft" title={oriName}>
          {oriName}
        </Tooltip>
      ), 
    },  
    {  
      title: t('dictionary.type'),  
      dataIndex: 'type',  
      key: 'type',  
      ellipsis: {
        showTitle: false,
      },
    render: (type) => (
        <Tooltip placement="topLeft" title={type}>
          {type}
        </Tooltip>
      ), 
    },  
    {  
      title: t('dictionary.remark'),  
      dataIndex: 'remark',  
      key: 'remark',  
      ellipsis: {
        showTitle: false,
      },
    render: (remark) => (
        <Tooltip placement="topLeft" title={remark}>
          {remark}
        </Tooltip>
      ), 
    },  
    {  
      title: t('dictionary.keyField'),  
      dataIndex: 'keyField',  
      key: 'keyField',  
      ellipsis: {
        showTitle: false,
      },
    render: (keyField) => (
        <Tooltip placement="topLeft" title={keyField}>
          {keyField}
        </Tooltip>
      ), 
    },  
    {  
      title: t('action'),  
      key: 'action',
      width:180,
      render: (text, record) => (  
        <>  
           <Button type="link"  onClick={() => handleView(record)}>  
           {t('view')}  
          </Button> 
          <Button type="link" onClick={() => handleEdit(record)}>  
          {t('edit')}  
          </Button>  
          <Button type="link" danger onClick={() => handleDelete(record.id)}>  
          {t('delete')}   
          </Button>  
   
        </>  
      ),  
    }, 
  ]

  const handleView = (record) =>{
    SetisView(true)
    setTitle("查看/View")
    console.log(record,'record')
    form.setFieldsValue({ ...record });  
    setIsModalVisible(true);  
   }
 
   const handleEdit = (record) =>{
     SetisView(false)
     setTitle("修改/Edit")
     console.log(record,'record')
     form.setFieldsValue({ ...record });  
     setIsModalVisible(true);  
     // 这里可以添加打开模态框并显示编辑表单的逻辑  
   }
 
   const handleDelete = (key) =>{
     let inciIds = []
     inciIds.push(key)
     Modal.confirm({  
       title: 'Confirm Delete',  
       content: 'Please confirm to DELETE SELECTED RECORDS!',  
       onOk() {  
        delDictionary(inciIds).then(response=>{
            message.success("Success")
            setReloadNum(onReloadNum+1)
            fetchTab1Data()
         }) 
       },  
     }); 
   }

   const handleCancel = () => {  
    setIsModalVisible(false);  
  };  


  const handleAdd = () =>{
    SetisView(false)
    form.resetFields()
    setTitle("新增/New")
    showModal()
  }

  const showModal = () => {  
    setIsModalVisible(true);  
  };  

  
  const handleOk = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form.getFieldsValue(); 
    
    if(Title=='修改/Edit'){
        updateDictionary(values).then(response => {
        message.success("成功")
        setIsModalVisible(false);
        setReloadNum(onReloadNum+1)
        fetchTab1Data()
       });  
      }else{
        addDictionary(values).then(response => {
          message.success("成功")
          setIsModalVisible(false);
          setReloadNum(onReloadNum+1)
          fetchTab1Data()
         });
      }

    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  
  

  // 定义下拉框的选项  
  const options = [  
      { label: '数字型', value: 'num' },  
      { label: '文字型', value: 'str' },  
    ];  
  const options2 = [  
      { label: 'Yes', value: 'Yes' },  
      { label: 'No', value: 'No' },  
    ]; 

    const expandedRowRender = (record) => {  
      // 如果record有subData属性，则渲染子表格  
      if (record.dataDictionaryList && record.dataDictionaryList.length > 0) {  
        // 使用subData作为子表格的数据源  
        return <Table columns={expandedColumns} dataSource={record.dataDictionaryList} pagination={false} />;  
      }  
      return null; // 如果没有子数据，则不渲染内容  
    };  
    
    // 自定义是否可展开的函数  
    const rowExpandable = (record) => record.typeName !== 'Not Expandable';  
  return (  
    <div>
    <Card>
        <Button size='small' onClick={handleAdd} type="primary" style={{marginBottom:'2%'}}>{t('add')}</Button>  
        <Table  
          dataSource={tab1Data}  
          columns={columnsTab1}
          pagination={false} 
          expandable={{  
            expandedRowRender,  
            rowExpandable,  
          }}  
        />  
    </Card>
    <Modal  
          title={Title}
          visible={isModalVisible}  
          onOk={handleOk}  
          onCancel={handleCancel}  
        >  
          <Form form={form} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}   
            <Form.Item  
              name="nameCn"  
              label={t('dictionary.nameCn')} 
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="nameEn"  
              label={t('dictionary.nameEn')}  
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="oriName"  
              label={t('dictionary.oriName')}  
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="type"  
              label={t('dictionary.type')}  
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="remark"  
              label={t('dictionary.remark')} 

            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="keyField"  
              label={t('dictionary.keyField')} 

            >  
              <Select disabled={isView}>
              <Select.Option value="Y">Y</Select.Option>
              <Select.Option value="N">N</Select.Option>
              </Select>  
            </Form.Item> 
          </Form>  
        </Modal>  
 
    </div>
  );  
};  
  
export default dictionary;